package com.example.expinterview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.example.expinterview.dto.IntegralDto;
import com.example.expinterview.entity.EiBuy;
import com.example.expinterview.entity.EiList;
import com.example.expinterview.entity.EiUser;
import com.example.expinterview.entity.ResultBody;
import com.example.expinterview.entity.enums.ErrorCodeEnum;
import com.example.expinterview.mapper.EiBuyMapper;
import com.example.expinterview.mapper.EiListMapper;
import com.example.expinterview.mapper.EiUserMapper;
import com.example.expinterview.service.IEiListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @classname: EiListServiceImpl
 * @description: TODO
 * @author: kaiser
 * @date: 2021/10/18 22:00
 * @version: 1.0
 */
@Service
public class EiListServiceImpl extends ServiceImpl<EiListMapper, EiList> implements IEiListService {

    private final EiBuyMapper buyMapper;
    private final EiUserMapper mapper;

    @Autowired
    public EiListServiceImpl(EiBuyMapper buyMapper, EiUserMapper mapper) {
        this.buyMapper = buyMapper;
        this.mapper = mapper;
    }

    @Override
    public ResultBody listById(Long userId) {
        List<EiList> list = baseMapper.selectList(new QueryWrapper<EiList>().eq("user_id", userId).orderByDesc("gmt_create"));
        return ResultBody.list(list);
    }

    @Override
    public ResultBody create(IntegralDto dto) {
        EiUser user = mapper.selectById(dto.getUserId());
        if (Objects.isNull(user)) {
            return ResultBody.fail(ErrorCodeEnum.USER_ERROR);
        } else {
            int value;
            Integer integral = user.getIntegral();
            Boolean type = dto.getType();
            if (type) {
                value = integral + dto.getValue();
            } else {
                if (integral.compareTo(dto.getValue()) > -1) {
                    value = integral - dto.getValue();
                } else {
                    return ResultBody.fail(ErrorCodeEnum.INTEGRAL_ERROR);
                }
            }
            EiList li = new EiList();
            li.setReason(dto.getReason());
            li.setUserId(dto.getUserId());
            li.setExValue(integral);
            li.setValue(dto.getValue());
            li.setAfterValue(value);
            li.setType(dto.getType());
            user.setIntegral(value);
            EiBuy eiBuy = new EiBuy();
            eiBuy.setUserId(dto.getUserId());
            eiBuy.setArticleId(dto.getArticleId());
            return ResultBody.status(SqlHelper.retBool(baseMapper.insert(li)) && SqlHelper.retBool(mapper.updateById(user)) && SqlHelper.retBool(buyMapper.insert(eiBuy)));
        }
    }
}
